package com.fmatos.service.album.downloader.rss;

import java.net.MalformedURLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.tomcat.util.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fmatos.service.album.domain.Photo;
import com.sun.syndication.feed.synd.SyndEnclosureImpl;
import com.sun.syndication.feed.synd.SyndEntryImpl;

public class CustomRssDownloader extends AbstractRssDownloader {

	private static final Logger LOGGER = LoggerFactory.getLogger(CustomRssDownloader.class);
	
	private final String url;
	
	public CustomRssDownloader(String url) {
		this.url = url;
	}
	
	@Override
	public String getDownloaderName() {
		return "Custom url";
	}

	@Override
	public String getFeedUrl() {
		return url;
	}

	@Override
	public void processEntry(SyndEntryImpl entry, List<Photo> photoList) {
		
		String imageRegex = getImageTagRegex(); 
		Pattern imagePattern = Pattern.compile(imageRegex);
		
		String html = "";
		if ( entry.getDescription() != null ) {
			html += entry.getDescription().getValue();
		}
		
		if ( entry.getContents() != null && entry.getContents().size() > 0) {
			html += entry.getContents();
		}

		Collection<String> imageUrlList = new HashSet<String>();
		
		if ( entry.getEnclosures() != null && entry.getEnclosures().size() > 0 && entry.getEnclosures().get(0) instanceof SyndEnclosureImpl) {
			SyndEnclosureImpl enclosureData = (SyndEnclosureImpl) entry.getEnclosures().get(0);
			if ( enclosureData.getUrl() != null ) {
				imageUrlList.add(enclosureData.getUrl());
			}
			
			if (  enclosureData.getUrl() != null ) {
				html += enclosureData.getUrl();
			}
		}
				
		findImages(html, imagePattern,imageUrlList);

//		LOGGER.info("Scanning entry");
		if ( imageUrlList != null ) {
			
			String description = html;
			for ( String imageUrl : imageUrlList ) {
				// TODO optimize this method
				Photo ph = new Photo(transformUrlToFullSize(imageUrl),
						transformUrlToThumbnail(imageUrl),
						entry.getLink().trim(),
						entry.getTitle().trim());
	
				if ( entry.getPublishedDate() != null ) {
					ph.setDate(entry.getPublishedDate()); 
				}
				ph.setDescription(description);
				photoList.add(ph);
			}
		}

	}
	
	/**
	 * Finds multiple images in the containing text.
	 * TODO this method is dangerous, it can enter an infinite loop and blow the stack if a malformer regex is used
	 * @param text where to search for img tags
	 * @param imagePattern
	 * @return List of well formed urls
	 */
	private Collection<String> findImages(String text,Pattern imagePattern,Collection<String> imageUrlList) {
		
		text = text.replace("\n", ""); // godamnit, matcher cant get past new line!!!
		
		Matcher str = imagePattern.matcher(text);
		String imageUrl = null;
		if ( str.find()) {
			imageUrl = str.group(3);
			try {
				new URL(imageUrl); // this line detects malformed urls and throws an exception
//				LOGGER.info("Found an image {}" , str.group(3) );
				imageUrlList.add(imageUrl);
			} catch (MalformedURLException e) {
//				LOGGER.warn("malformed url {} "  , imageUrl);
				imageUrl = null;
			} 
					
			findImages(str.group(1), imagePattern,imageUrlList); // one of these should not be necessary, after all either the regex is greedy or lazy
			findImages(str.group(4), imagePattern,imageUrlList);
		}
		
		return imageUrlList;
	}
	
	@Override
	public String transformUrlToFullSize(String url) {
	
		// National geo http://images.nationalgeographic.com/exposure/core_media/ngphoto/image/86761_0_360x270.jpg
		//	            http://images.nationalgeographic.com/wpf/media-live/photos/000/867/cache/bay-arcachon-france-aerial_86761_990x742.jpg
		

//		http://images.nationalgeographic.com/wpf/media-live/photos/000/118/cache/hubble-deep-field-distant-galaxies_11803_990x742.jpg
//		http://news.nationalgeographic.com/news/images/thumbs/100105-earliest-galaxies-hubble-deep-universe_60x40.jpg
				
		url = url.replace("360x270", "990x742"); // National Geo
		url = url.replace("236x", "originals"); // Pinterest
		url = url.replace("jpl.nasa.gov/thumb", "jpl.nasa.gov/jpeg"); // JPL
//		url = url.replace("www.jpl.nasa.gov/images/earth.*-226.jpg","www.jpl.nasa.gov/images/earth.*-16.jpg");
		url = url.replace("-226.jpg","-16.jpg"); // JPL multimedia news
				
		
//		http://www.jpl.nasa.gov/images/earth/20141229/tropicalforest-16.jpg
//		http://www.jpl.nasa.gov/images/earth/20141229/tropicalforest-226.jpg
			
		// http://photojournal.jpl.nasa.gov/jpeg/PIA18993.jpg
		// http://photojournal.jpl.nasa.gov/thumb/PIA18993.jpg
		
		// http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/592260main_blackhole-outflow.jpg?itok=Rf5p_u0c
		// http://www.nasa.gov/content/black-hole-friday/#.VKQEHHVdW00
		// http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/592260main_blackhole-outflow.jpg?itok=Rf5p_u0c
		
		
		// http://www.botanicalgarden.ubc.ca/potd/images/2010/wyethia-helianthoides1.jpg
		// http://www.botanicalgarden.ubc.ca/potd/images/2010/wyethia-helianthoides1-thumb-150x100-1622.jpg
		return super.transformUrlToFullSize(url);
	}
}
